<template>
  <view>
    <view class="head">
      <view class="search-bar">
        <u-search
            @change="search()"
            @search="search()"
            @clear="clear()"
            v-model="keyword"
            shape="round"
            clearabled
            :show-action="false"
            placeholder="请输入书名或借阅人..."
        ></u-search>
      </view>
      <view class="subsection">
        <u-subsection
            @change="subsectionSwitch()"
            :list="subsection.list"
            mode="button"
            :current="subsection.curIndex"
            :active-color="subsection.list[subsection.curIndex].activeColor"
            bold
            font-size="14"
        ></u-subsection>
      </view>
    </view>
    <view class="content">
      <u-cell-group :border="false">
        <view class="item" v-for="(item, index) in subDataList_" :key="index" v-if="!loadingStatus">
          <u-cell :is-link="true" @click="navigate2RecordManage(item._id)">
            <!--封面-->
            <view slot="icon" class="cover">
              <u-image :src="item.bookId[0].cover" mode="aspectFill" width="10vw" height="14.9vw"></u-image>
            </view>
            <!--书名-->
            <view slot="title" class="title">
              <u-text :text="item.bookId[0].name" :lines="1"></u-text>
            </view>
            <!--详细信息-->
            <view slot="label" class="text">
              <u-text :text="`借阅人：${item.userId[0].name}`" type="primary" size="12"></u-text>
              <u-text :text="`借阅日期：${getTime(item.createDate)}`" type="info" size="12"></u-text>
            </view>
            <!-- ”全部“标签页右侧按钮 -->
            <view slot="value">
              <!-- TODO button -->
              <u-button
                  @click.native.stop="bookReturn(item._id,item.bookId[0]._id)"
                  v-if="subsection.curIndex === 1"
                  text="归还"
                  :custom-style="{border:'none',color:'#ff9900'}"
                  :hairline="false">
              </u-button>
            </view>
          </u-cell>
        </view>
        <view v-for="n in 9" v-if="loadingStatus">
          <view class="loading">
            <u-skeleton rows="2" :avatar="true" :title="false" avatar-size="10vw" avatar-shape="square"></u-skeleton>
          </view>
        </view>
      </u-cell-group>
      <view class="divider">
        <u-divider :text="`共${listLength}条借阅记录`"></u-divider>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      subsection: {
        list: [
          {name: '借阅中', index: 0, activeColor: '#19be6b'},
          {name: '待确认', index: 1, activeColor: '#ff9900'},
          {name: '已逾期', index: 2, activeColor: '#fa3534'},
          {name: '已归还', index: 3, activeColor: '#909399'}
        ],
        curIndex: 0
      },
      keyword: '',
      loadingStatus: true,
      dataList: [],
      subDataList: [],
      // 用于搜索
      subDataList_: [],
      listLength: 0
    }
  },
  methods: {
    async onLoad() {
      console.log('userinfo', uni.getStorageSync('userInfo'))
      this.loadingStatus = true
      await this.getData(this.subsection.curIndex)
      this.loadingStatus = false
    },
    async onPullDownRefresh() {
      this.loadingStatus = true
      await this.getData(this.subsection.curIndex)
      this.loadingStatus = false
    },
    async getData(index) {
      let db = uniCloud.database()
      let book = db.collection('book').field('_id,name,cover').getTemp()
      let user = db.collection('user').field('_id,name').getTemp()
      this.dataList = (await db.collection('record', book, user).orderBy('createDate', 'desc').get()).result.data
      this.subsectionSwitch(index)
    },
    subsectionSwitch(index) {
      this.subsection.curIndex = index
      switch (index) {
        case 0:
          this.subDataList = this.dataList.filter(item => item.status === 'borrow')
          this.search()
          break
        case 1:
          this.subDataList = this.dataList.filter(item => item.status === 'backing')
          this.search()
          break
        case 2:
          this.subDataList = this.dataList.filter(item => item.status === 'backing' && this.isOverdue(item.createDate, item.borrowTime))
          this.search()
          break
        case 3:
          this.subDataList = this.dataList.filter(item => item.status === 'back')
          this.search()
          break
        default:
          break
      }
    },
    navigate2RecordManage(recordId) {
      uni.navigateTo({
        url: `/pages/RecordManage?recordId=${recordId}`
      })
    },
    search() {
      this.subDataList_ = this.subDataList.filter(item => item.bookId[0].name.indexOf(this.keyword, 0) !== -1 || item.userId[0].name.indexOf(this.keyword, 0) !== -1)
    },
    clear() {
      this.keyword = ''
    },
    bookReturn(recordId, bookId) {
      let _this = this
      uni.showModal({
        title: '确认归还',
        content: '是否归还此图书?',
        success(res) {
          if (res.confirm) {
            new Promise((resolve) => {
              let db = uniCloud.database()
              // 修改record为”已归还“
              db.collection('record').doc(recordId).update({status: 'back'})
              // 新增record_action
              db.collection('record_action').add({
                userId: uni.getStorageSync('userInfo')._id,
                recordId,
                status: 'back'
              })
              // 修改book的status为true
              db.collection('book').doc(bookId).update({status: true})
              resolve()
            }).then(() => {
              uni.showToast({
                title: '归还成功!',
                icon: 'success'
              })
            }).catch(err => {
              uni.showToast({
                title: err.message || '归还失败!',
                icon: 'error'
              })
            }).finally(() => {
              _this.getData(_this.subsection.curIndex)
            })
          }
        }
      })
    }
  },
  computed: {
    getTime() {
      return function (timestamp) {
        if (timestamp === null || timestamp === '') return ''
        let date = new Date(timestamp)
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        return String(Y + M + D)
      }
    },
    /**
     * 判断是否逾期
     *
     * @param borrowDate 借阅日期(时间戳)
     * @param duration 借阅时长(天)
     */
    isOverdue() {
      return function (borrowDate, duration) {
        return +borrowDate + +duration * 86400000 < Date.now()
      }

    }
  },
  watch: {
    subDataList_: {
      handler(value) {
        this.listLength = value.length
      },
      deep: true
    }
  }
}
</script>

<style lang="scss" scoped>
.head {
  margin: 0 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;

  .search-bar {
    width: 100%;
  }

  .subsection {
    width: 100%;
    margin-top: 10px;
  }
}

.content {
  margin-top: 10px;

  .divider {
    margin: 0 15px;
  }

  .item {
    .title {
      margin-left: 10px;
    }

    .text {
      margin-left: 10px;
      margin-top: 2px;
    }
  }

  .loading {
    margin: 10px 15px;
  }
}
</style>
